package selenium.lessons.pages;

import com.gargoylesoftware.htmlunit.javascript.TimeoutError;
import org.openqa.selenium.*;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: Administrator
 * Date: 19.03.13
 * Time: 21:47
 * To change this template use File | Settings | File Templates.
 */
public class HomePage extends Page{
    private boolean acceptNextAlert = true;

    public HomePage(WebDriver webDriver) {
        super(webDriver);
    }

    public boolean deleteMovie(String siteUrl, String title)
    {
        try {
            webDriver.findElements(By.cssSelector("div[title="+title+"]")).get(0).click();
            webDriver.findElement(By.cssSelector("img[alt=\"Remove\"]")).click();
            closeAlertAndGetItsText().matches("^Are you sure you want to remove this[\\s\\S]$");
            return true;
        }
        catch (Exception e) {
            return false;
        }
    }

    public boolean addMovie(String siteUrl, String mName, String mYear)
    {
       try {
           webDriver.findElement(By.cssSelector("a[href$=add]")).click();
           webDriver.findElement(By.name("name")).sendKeys(mName);
           webDriver.findElement(By.name("year")).sendKeys(mYear);
           webDriver.findElement(By.name("submit")).click();
           webDriver.get(siteUrl + "php4dvd/#!/sort/name asc/");
           return true;
       }
       catch (Exception e) {
           return false;
       }
    }

    public boolean waitForMovieAppear(String title)
    {
        WebDriverWait wait = new WebDriverWait(webDriver, 10);
        try {
            WebElement element = wait.until(ExpectedConditions.presenceOfElementLocated(By.cssSelector("div[title=" + title + "]")));
            return true;
        }
        catch (Exception e)
        {
            return false;
        }
    }

    public void findMovie(String mName)
    {
        webDriver.findElement(By.id("q")).clear();
        webDriver.findElement(By.id("q")).sendKeys(mName);
        webDriver.findElement(By.id("q")).sendKeys(Keys.RETURN);
    }

    public List<WebElement> getMovieList(String title)
    {
        return webDriver.findElements(By.cssSelector("div[title=" + title + "]"));
    }

    private String closeAlertAndGetItsText() {
        try {
            Alert alert = webDriver.switchTo().alert();
            String alertText = alert.getText();
            if (acceptNextAlert) {
                alert.accept();
            } else {
                alert.dismiss();
            }
            return alertText;
        } finally {
            acceptNextAlert = true;
        }
    }
}
